<template>
  <n-grid cols="1" responsive="screen" class="-mt-5">
    <n-grid-item>
      <n-list>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text @click="openModalFn">{{
              $t('common.button.edit')
            }}</n-button>
          </template>
          <n-thing :title="getPageLangValueFn('form.accountPassword')">
            <!-- <template #description
              ><span class="text-gray-400">绑定手机和邮箱，并设置密码，帐号更安全</span></template
            > -->
          </n-thing>
        </n-list-item>
        <!-- <n-list-item>
          <template #suffix>
            <n-button type="primary" text>修改</n-button>
          </template>
          <n-thing title="绑定手机">
            <template #description
              ><span class="text-gray-400">已绑定手机号：+86189****4877</span></template
            >
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text>设置</n-button>
          </template>
          <n-thing title="密保问题">
            <template #description
              ><span class="text-gray-400"
                >未设置密保问题，密保问题可有效保护账户安全</span
              ></template
            >
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text>修改</n-button>
          </template>
          <n-thing title="个性域名">
            <template #description
              ><span class="text-gray-400">已绑定域名：https://www.naiveui.com</span></template
            >
          </n-thing>
        </n-list-item> -->
      </n-list>
    </n-grid-item>
  </n-grid>

  <DFModal @register="modalRegister" ref="basicModalRef" class="basicModal" @on-ok="okModalFn">
    <template #default>
      <DFForm @register="modalFormRegister" class="basicForm" />
    </template>
  </DFModal>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick, computed } from 'vue';
  import { useMessage, FormItemRule } from 'naive-ui';
  import { DFModal, useModal } from '@/components/DFModal';
  import { DFForm, FormSchema, useForm } from '@/components/DFForm/index';

  import { checkPassWordFn } from '@/utils/formCheck';

  import { updatePassword } from '@/api/system/user';

  import { cloneDeep } from 'lodash-es';

  // import { defaultPassWord } from '@/views/permission/system/user/defaultPwd';

  import { useUserStore } from '@/store/modules/user';

  import { encrypt } from '@/utils/jsencrypt';

  import { useMixins } from '@/hooks/useMixins';

  import { t } from '@/i18n';

  const { getPageLangValueFn } = useMixins();

  const basicModalRef: any = ref(null);

  const message = useMessage();

  const editDisabled = ref(false);

  const userStore = useUserStore();

  const userInfo: object = userStore.getUserInfo || {};

  const userName = userInfo['userName'] || '';

  const modalFormSchemas: FormSchema[] = [
    {
      field: 'oldPassword',
      component: 'NInput',
      label: 'oldPassword',
      defaultValue: null,
      hidden: editDisabled,
      componentProps: {
        minlength: 6,
        maxlength: 20,
        type: 'password',
        'show-count': true,
        clearable: true,
        'show-password-on': 'click',
      },
      rules: [
        {
          required: true,
          validator(_rule: FormItemRule, value: string) {
            return checkPassWordFn(value, true);
          },
          trigger: ['blur'],
        },
      ],
    },
    {
      field: 'newPassword',
      component: 'NInput',
      label: 'newPassword',
      defaultValue: null,
      hidden: editDisabled,
      componentProps: {
        minlength: 6,
        maxlength: 20,
        type: 'password',
        'show-count': true,
        clearable: true,
        'show-password-on': 'click',
      },
      rules: [
        {
          required: true,
          validator(_rule: FormItemRule, value: string) {
            return checkPassWordFn(value, true);
          },
          trigger: ['blur'],
        },
        // {
        //   validator(_rule: FormItemRule, value: string) {
        //     const data = { ...cloneDeep(getModalFormValFn()) };

        //     const { oldPassword = '' } = data;

        //     if (value === defaultPassWord) {
        //       return new Error(getPageLangValueFn('tipsMsg.error1'));
        //     } else if (value && value.indexOf(userName) !== -1) {
        //       return new Error(getPageLangValueFn('tipsMsg.error2'));
        //     } else if (value && value === oldPassword) {
        //       return new Error(getPageLangValueFn('tipsMsg.error3'));
        //     }

        //     return true;
        //   },
        //   trigger: ['blur'],
        // },
      ],
    },
    {
      field: 'confirmPassword',
      component: 'NInput',
      label: 'confirmPassword',
      defaultValue: null,
      hidden: editDisabled,
      componentProps: {
        minlength: 6,
        maxlength: 20,
        type: 'password',
        'show-count': true,
        clearable: true,
        'show-password-on': 'click',
      },
      rules: [
        {
          required: true,
          validator(_rule: FormItemRule, value: string) {
            return checkPassWordFn(value, true);
          },
          trigger: ['blur'],
        },
        {
          validator(_rule: FormItemRule, value: string) {
            const data = { ...cloneDeep(getModalFormValFn()) };

            const { newPassword = '' } = data;

            if (value !== newPassword) {
              return new Error(getPageLangValueFn('tipsMsg.error4'));
            }

            return true;
          },
          trigger: ['blur'],
        },
      ],
    },
  ];

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: t('common.button.edit'),
  });

  const [modalFormRegister, { validate, getFieldsValue: getModalFormValFn }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    showActionButtonGroup: false,
    schemas: modalFormSchemas,
  });

  const okModalFn = async () => {
    try {
      const isSubmit = await validate();

      if (!isSubmit) {
        modalSubmitFn();
      }
    } catch (e) {
      console.log(e);

      setSubLoading(false);
    }
  };

  const modalSubmitFn = async () => {
    try {
      const data: any = { ...cloneDeep(getModalFormValFn()) };

      data['oldPassword'] = encrypt(data['oldPassword']);

      data['newPassword'] = encrypt(data['newPassword']);

      data['userName'] = userName;

      delete data['confirmPassword'];

      const res = await updatePassword(data);

      if (res) {
        const { message: msg = '' } = res;

        userStore.setUserInfo({
          ...userInfo,
          firstStatus: 1,
        });

        closeModal();

        msg && message.success(msg);
      } else {
        setSubLoading(false);
      }
    } catch (e) {
      setSubLoading(false);
      console.log(e);
    }
  };

  const openModalFn = async () => {
    openModal();

    nextTick(() => {
      userStore.setOpenResetPwdModal(false);
    });
  };

  const openResetPwdModal = computed(() => userStore.openResetPwdModal);

  watch(
    openResetPwdModal,
    (val) => {
      if (val) {
        nextTick(() => {
          openModalFn();
        });
      }
    },
    { immediate: true, deep: true }
  );
</script>
